package com.culture.config.common.advice;

import java.util.HashMap;
import java.util.Map;

import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.culture.config.common.model.BusinessException;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;

@Slf4j
@ControllerAdvice
public class ControllerAdviceHandle {
    
    @InitBinder
    public void handleException(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleException(Exception ex) {
    	Map<String, Object> map = new HashMap<>();
    	if(ex instanceof BusinessException) {
    		map.put("code", ((BusinessException)ex).getBusinessExceptionCode());    	      
    	    map.put("message",  ((BusinessException)ex).getBusinessExceptionMessage());
    		return map;
    	}       
        map.put("code", 500);       
        map.put("message", ex.toString());
        log.error(String.valueOf(map.get("msg")));
        return map;
    }
}